<template>
	<div class="wx">微信非静默授权</div>
</template>
<script>
import axios from 'axios';
import wx from 'weixin-js-sdk';

export default {
	data() {
		return {
			baseUrl: 'https://dapp.kcguoyi.com/api',
			code: '',
			doctorCode: null,
			wxmsg: {},
			toast: null,
			showPage: true,
		};
	},
	mounted() {
		if (this.is_weixn()) {
			if (!this.getUrlCode('code')) {
				let host = window.location.host;
				let url =
					'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8ffe335e09133b84&redirect_uri=https%3A%2F%2F' +
					host +
					'%2Fquestionnaire%2F%23%2FsanFuTang_sh%2Fpatient%2Findex&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect';
				window.location.replace(url);
			} else {
				this.checkWeChatCode();
			}
		} else {
			this.$dialog.alert({
				message: '请使用微信扫描二维码',
			});
		}
	},
	methods: {
		is_weixn() {
			var ua = navigator.userAgent.toLowerCase();
			if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				return true;
			} else {
				return false;
			}
		},
		getUrlCode(name) {
			return (
				decodeURIComponent(
					(new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
						location.href
					) || [, ''])[1].replace(/\+/g, '%20')
				) || null
			);
		},
		checkWeChatCode() {
			this.toast = this.$toast.loading({
				message: '加载中...',
				forbidClick: true,
				duration: 10000,
			});
			let code = this.getUrlCode('code');
			this.code = code;
			this.doctorCode = this.getUrlCode('state'); //514088
			localStorage.setItem('code', this.doctorCode);
			this.getOpenid(code);
		},
		// 获取openid
		getOpenid(code) {
			let url = this.baseUrl + '/service/mini/getAccessToken';
			axios.post(url, { code: code }).then((res) => {
				this.toast.clear();
				if (res.data.code == 0) {
					this.wxmsg = res.data.body;
					localStorage.setItem('wxmsg', JSON.stringify(res.data.body));
				} else {
					this.$router.replace({ path: '/sanFuTang_sh/patient/order' });
				}
			});
		},
		getJssdk() {
			let that = this;
			let url = this.base_url + '/service/sanhan3fu/sign';
			axios.post(url, { url: window.location.href }).then((res) => {
				let result = res.data.body;
				wx.config({
					debug: false, // 开启调试模式,
					appId: 'wx8ffe335e09133b84', // 必填，企业号的唯一标识，此处填写企业号corpid
					timestamp: result.timestamp, // 必填，生成签名的时间戳
					nonceStr: result.nonceStr, // 必填，生成签名的随机串
					signature: result.signature, // 必填，签名，见附录1
					jsApiList: ['openLocation'], // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
				});

				wx.ready(function () {
					wx.getLocation({
						success: function (res) {
                            console.log(res.latitude);
							that.latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
							that.longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
						},
					});
				});
			});
		},
	},
};
</script>
